<template>
  <div>
    <el-dialog v-loading.lock="loading" class="base-dialog system-user-dialog" :append-to-body="true" :title="title"
      align="center" :visible.sync="dialogFormVisible" @closed="closeDialog">
      <el-form ref="formData" class="base-pipeline-layout system-user-form" label-width="100px" :model="formData"
        :rules="formDataRules" status-icon>
        <el-form-item label="所属仓库" :label-width="formLabelWidth" prop="storageId" :error="errorMsg.storageId">
          <el-select v-model="formData.storageId">
            <el-option v-for="item in storageOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库区名称" :label-width="formLabelWidth" prop="areaName" :error="errorMsg.areaName">
          <el-input v-model="formData.areaName" autocomplete="off" clearable maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="库区编码" :label-width="formLabelWidth" prop="areaNumber" :error="errorMsg.areaNumber">
          <el-input v-model="formData.areaNumber" autocomplete="off" clearable maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="库区类型" :label-width="formLabelWidth" prop="areaType" :error="errorMsg.areaType">
          <el-select v-model="formData.areaType" @change="selectAreaType">
            <el-option v-for="item in areaTypeOptions" :key="item.id" :label="item.name"
              :value="item.value * 1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="作业方式" :label-width="formLabelWidth" prop="jobWay" :error="errorMsg.jobWay">
          <el-select v-model="formData.jobWay">
            <el-option v-for="item in jobWayOptions" :key="item.id" :label="item.name"
              :value="item.value * 1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="isSmartDevice" label="关联设备ID" :label-width="formLabelWidth" prop="relatedDeviceID"
          :error="errorMsg.relatedDeviceID">
          <el-input v-model="formData.relatedDeviceID" autocomplete="off" clearable maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="推荐优先级" :label-width="formLabelWidth" prop="level" :error="errorMsg.level">
          <el-input v-model="formData.level" autocomplete="off" type="number" placeholder="请输入1~99数字,数字越小优先级越高"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="存储条件" :label-width="formLabelWidth" prop="storageConditions"
          :error="errorMsg.storageConditions">
          <el-select v-model="formData.storageConditions">
            <el-option v-for="item in storageConditionsOptions" :key="item.id" :label="item.name"
              :value="item.value * 1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" prop="status" :error="errorMsg.status">
          <el-select v-model="formData.status">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')">保 存</el-button>
        <el-button @click="closeDialog">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDictList } from "../../../api/System/SystemDict.js";
import { getById, create, update, getStorageList } from "../../../api/Storage/StorageArea.js";

export default {
  name: "StorageAreaEdit",
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      loading: false,
      dialogFormVisible: false,
      isSmartDevice: false,
      formLabelWidth: "100px",
      title: "",
      storageOptions: [],
      areaTypeOptions: [],
      jobWayOptions: [],
      storageConditionsOptions: [],
      initData: {
        id: 0,
        storageId: "",
        areaName: "",
        areaNumber: "",
        areaType: 100,
        relatedDeviceID: "",
        description: "",
        level: "",
        jobWay: 100,
        storageConditions: "",
        status: 1,
        operatorId: 0,
      },
      formData: {
        id: 0,
        storageId: "",
        areaName: "",
        areaNumber: "",
        areaType: 100,
        relatedDeviceID: "",
        description: "",
        level: "",
        jobWay: 100,
        storageConditions: "",
        status: 1,
        operatorId: 0,
      },
      formDataRules: {
        storageId: [
          {
            required: true,
            trigger: "blur",
            message: "请选择所属仓库",
          },
        ],
        areaName: [
          {
            required: true,
            trigger: "blur",
            message: "请填写库区名称"
          },
        ],
        areaNumber: [
          {
            required: true,
            trigger: "blur",
            message: "请填写库区编码"
          },
        ],
        areaType: [
          {
            required: true,
            trigger: "blur",
            message: '请选择库区类型',
          },
        ],
        relatedDeviceID: [
          {
            required: false,
            trigger: "blur",
            message: "智能设备的关联设备ID必填",
          },
        ],
        level: [
          {
            required: true,
            trigger: "blur",
            validator: this.validateLevel,
          },
        ],
        jobWay: [
          {
            required: true,
            trigger: "blur",
            message: "请选择作业方式",
          },
        ],
        storageConditions: [
          {
            required: true,
            trigger: "blur",
            message: "请选择存储条件",
          },
        ],
        status: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
      },
      initErrorMsg: {
        storageId: "",
        areaName: "",
        areaNumber: "",
        areaType: "",
        relatedDeviceID: "",
        description: "",
        level: "",
        jobWay: "",
        storageConditions: "",
        status: "",
      },
      errorMsg: {
        storageId: "",
        areaName: "",
        areaNumber: "",
        areaType: "",
        relatedDeviceID: "",
        description: "",
        level: "",
        jobWay: "",
        storageConditions: "",
        status: "",
      },
    };
  },
  watch: {
    value: function() {
      this.dialogFormVisible = this.value;
      if (this.value) {
        this.init();
      }
    },
  },
  methods: {
    async init() {
      this.getOptions();
      if (this.editId) {
        this.title = "修改库区";
        this.formData.id = this.editId;
        getById({ id: this.editId })
          .then((res) => {
            this.formData = res.data ? res.data : {};
            this.isSmartDevice = this.formData.areaType !== 100;
          }).finally(() => {
            this.formLoading = false;
          });
      } else {
        this.title = "新增库区";
        this.formData.id = 0;
        this.loading = false;
        this.formData = this.initData;
        this.isSmartDevice = false;
      }
    },

    getOptions() {
      getDictList({ dictCode: "StorageArea_AreaTypeCode" }).then((res) => {
        this.areaTypeOptions = res.data;
      });
      getDictList({ dictCode: "StorageArea_JobWayCode" }).then((res) => {
        this.jobWayOptions = res.data;
      });
      getDictList({ dictCode: "StorageProduct_StorageConditionCode" }).then((res) => {
        this.storageConditionsOptions = res.data;
      });
      getStorageList({ type: 0 })
        .then((res) => {
          this.storageOptions = res.data.dataList ? res.data.dataList : [];
        }).catch(() => { });
    },

    selectAreaType(val) {
      if (val === 100) {
        this.formData.relatedDeviceID = '';
        this.isSmartDevice = false;
        this.formDataRules.relatedDeviceID[0].required = false;
      } else {
        this.isSmartDevice = true;
        this.formDataRules.relatedDeviceID[0].required = true;
      }
    },
    closeDialog() {
      this.$refs.formData.resetFields();
      this.$emit("input", false);
      this.$parent.getList();
    },
    onSubmit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          if (this.editId) {
            update(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            create(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("storageId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("areaName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("areaNumber", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("areaType", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("relatedDeviceID", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("description", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("level", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("jobWay", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("storageConditions", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("status", this.errorMsg, res.msg);
      }
    },
    validateLevel(rule, value, callback) {
      if (/^(0|[1-9][0-9]*)$/.test(this.formData.level)) {
        const num = parseInt(this.formData.level)
        if (num > 99 || value < 1) {
          callback(
            new Error("必须是1~99数字")
          );
        } else {
          callback();
        }
      } else {
        callback(
          new Error("必须是1~99数字")
        );
      }
    },
  },
};
</script>

